package com.kaver.modular.dc.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.kaver.core.base.controller.BaseController;
import com.kaver.core.base.tips.ErrorTip;
import com.kaver.core.common.annotion.Permission;
import com.kaver.core.common.exception.BizExceptionEnum;
import com.kaver.core.exception.BzException;
import com.kaver.core.log.LogObjectHolder;
import com.kaver.core.node.ZTreeNode;
import com.kaver.core.page.PageBT;
import com.kaver.core.page.PageInfoBT;
import com.kaver.core.shiro.ShiroKit;
import com.kaver.core.shiro.ShiroUser;
import com.kaver.core.util.ToolUtil;
import com.kaver.modular.dc.service.IDcAppService;
import com.kaver.modular.dc.service.IDcAppUserService;
import com.kaver.modular.system.model.DcApp;
import com.kaver.modular.system.model.DcAppUser;
import com.kaver.modular.system.model.User;
import com.kaver.modular.system.service.IDeptService;
import com.kaver.modular.system.service.IUserService;

/**
 * 应用管理控制器
 *
 * @author Roc
 * @Date 2019-01-29 10:53:32
 */
@Controller
@RequestMapping("/dcApp")
public class DcAppController extends BaseController {

	private String PREFIX = "/dc/dcApp/";

	@Autowired
	private IDcAppService dcAppService;
	@Autowired
	private IDeptService deptService;
	@Autowired
	private IUserService userService;
	@Autowired
	private IDcAppUserService dcAppUserService;

	/**
	 * 跳转到应用管理首页
	 */
	@RequestMapping("")
	public String index() {
		return PREFIX + "dcApp.html";
	}

	/**
	 * 跳转到添加应用管理
	 */
	@RequestMapping("/dcApp_add")
	public String dcAppAdd() {
		return PREFIX + "dcApp_add.html";
	}

	/**
	 * 跳转到修改应用管理
	 */
	@RequestMapping("/dcApp_update/{dcAppId}")
	public String dcAppUpdate(@PathVariable Integer dcAppId, Model model) {
		DcApp dcApp = dcAppService.selectById(dcAppId);
		model.addAttribute("item", dcApp);
		LogObjectHolder.me().set(dcApp);
		return PREFIX + "dcApp_edit.html";
	}

	/**
	 * 获取应用管理列表
	 */
	@RequestMapping(value = "/list")
	@ResponseBody
	public Object list(PageBT pageBT, String condition) {
		DcApp entity = new DcApp();
		Wrapper<DcApp> wrapper = new EntityWrapper<>(entity);
		wrapper.like("app_name", condition);
		return new PageInfoBT<>(
				dcAppService.selectPage(new Page<>(pageBT.getPageNumber(), pageBT.getPageSize()), wrapper));
	}

	/**
	 * 新增应用管理
	 */
	@Permission
	@RequestMapping(value = "/add")
	@ResponseBody
	public Object add(DcApp dcApp) {
		DcApp entity = new DcApp();
		entity.setAppName(dcApp.getAppName());
		Wrapper<DcApp> wrapper = new EntityWrapper<DcApp>(entity);
		int count = dcAppService.selectCount(wrapper);
		if (count > 0) {
			return new ErrorTip(500, "应用名已存在");
		}
		dcApp.setCreateTime(new Date());
		ShiroUser user = ShiroKit.getUser();
		dcApp.setCreateUser(user.getName());
		dcAppService.insert(dcApp);
		return SUCCESS_TIP;
	}

	/**
	 * 删除应用管理
	 */
	@Permission
	@RequestMapping(value = "/delete")
	@ResponseBody
	public Object delete(@RequestParam Integer dcAppId) {
		dcAppService.deleteById(dcAppId);
		return SUCCESS_TIP;
	}

	/**
	 * 修改应用管理
	 */
	@Permission
	@RequestMapping(value = "/update")
	@ResponseBody
	public Object update(DcApp dcApp) {
		DcApp app = dcAppService.selectById(dcApp.getId());
		if (app == null) {
			return new ErrorTip(500, "应用不存在");
		}
		if (dcApp.getAppName() != null && !dcApp.getAppName().equals(app.getAppName())) {
			DcApp entity = new DcApp();
			entity.setAppName(dcApp.getAppName());
			Wrapper<DcApp> wrapper = new EntityWrapper<DcApp>(entity);
			int count = dcAppService.selectCount(wrapper);
			if (count > 0) {
				return new ErrorTip(500, "应用名已存在");
			}
		}
		dcApp.setUpdateTime(new Date());
		ShiroUser user = ShiroKit.getUser();
		dcApp.setUpdateUser(user.getName());
		dcAppService.updateById(dcApp);
		return SUCCESS_TIP;
	}

	/**
	 * 应用管理详情
	 */
	@RequestMapping(value = "/detail/{dcAppId}")
	@ResponseBody
	public Object detail(@PathVariable("dcAppId") Integer dcAppId) {
		return dcAppService.selectById(dcAppId);
	}

	/**
	 * 获取用户树
	 */
	@RequestMapping(value = "/userTree/{appId}")
	@ResponseBody
	public List<ZTreeNode> userTree(@PathVariable("appId") Integer appId) {
		DcAppUser entity = new DcAppUser();
		entity.setAppId(appId);
		Wrapper<DcAppUser> wrapper = new EntityWrapper<DcAppUser>(entity);
		List<DcAppUser> appUsers = dcAppUserService.selectList(wrapper);
		Set<Integer> set = new HashSet<>();
		if (!CollectionUtils.isEmpty(appUsers)) {
			appUsers.forEach(action->{
				set.add(action.getUserId());
			});
			
		}
		List<ZTreeNode> newTree = new ArrayList<>();
		List<ZTreeNode> tree = this.deptService.tree();
		if (!CollectionUtils.isEmpty(tree)) {
			tree.forEach(action -> {
				newTree.add(action);
				User user = new User();
				user.setDeptid(action.getId().intValue());
				Wrapper<User> userwapper = new EntityWrapper<User>(user);
				List<User> list = userService.selectList(userwapper);
				if (!CollectionUtils.isEmpty(list)) {
					list.forEach(us -> {
						ZTreeNode treeNode = new ZTreeNode();
						if (set.contains(us.getId())) {
							treeNode.setChecked(true);
						}else {
							treeNode.setChecked(false);
						}
						treeNode.setId(us.getId().longValue());
						treeNode.setIsOpen(false);
						treeNode.setName(us.getName());
						treeNode.setOpen(false);
						treeNode.setpId(action.getId());
						newTree.add(treeNode);
					});
				}
			});
		}
		return newTree;
	}

	@RequestMapping("/app_assign/{appId}")
	public String roleAssign(@PathVariable Integer appId, Model model) {
		if (ToolUtil.isEmpty(appId)) {
			throw new BzException(BizExceptionEnum.REQUEST_NULL);
		}
		DcApp app = dcAppService.selectById(appId);
		model.addAttribute("appId", appId);
		model.addAttribute("appName", app.getAppName());
		return PREFIX + "app_userassign.html";
	}

	/**
	 * 应用分配用户
	 */
	@Permission
	@RequestMapping(value = "/setUser")
	@ResponseBody
	public Object setUser(@RequestParam Integer appId, @RequestParam String userIds) {
		String[] ids = userIds.split(",");
		if (ids == null || ids.length < 1) {
			throw new BzException(BizExceptionEnum.REQUEST_NULL);
		}
		DcAppUser entity = new DcAppUser();
		entity.setAppId(appId);
		Wrapper<DcAppUser> wrapper = new EntityWrapper<DcAppUser>(entity);
		dcAppUserService.delete(wrapper);
		ShiroUser user = ShiroKit.getUser();
		List<DcAppUser> entityList = new ArrayList<>();
		for (String id : ids) {
			DcAppUser appUser = new DcAppUser();
			appUser.setAppId(appId);
			appUser.setCreateTime(new Date());
			appUser.setCreateUser(user.getName());
			appUser.setUserId(Integer.valueOf(id));
			entityList.add(appUser);
		}
		dcAppUserService.insertBatch(entityList);
		return SUCCESS_TIP;
	}
}
